/*
 * @Descripttion: 
 * @Author: cuidm
 * @Date: 2022-06-30 14:01:31
 * @LastEditors: cuidm
 * @LastEditTime: 2022-08-12 12:31:59
 */
import React, { useState, useEffect } from "react";
import { Modal, Form, Button, Input,  message, Space, Checkbox, Row, Col, Popover } from "antd";
import cmdbres from "@/data/cmdbres";
import request from "@/utils/request";
import "./index.less";

const ServiceTemplateModal = ({info, biz, visible, setVisible, onAddFinish, history,getDeFaultValue})  => {
	const [form] = Form.useForm();
	const [loading, setLoading] = useState(false);
	const [templateData, setTemplateData] = useState([]);
	const [searchValue, setSearchValue] = useState('');

	useEffect(() => {
		getServiceTemplateData();
	}, []);

	useEffect(() => {
		if(visible && !loading) {
			onChange(getDeFaultValue())
		}
	}, [visible, loading])

	const getServiceTemplateData = async (params = { current: 1, pageSize: 10 }) => {
        try {
			if(!(biz && biz.cm_unid)) {
				console.log("请确认是否创建业务！");
				return;
			}
			setLoading(true);
            const res = await request({
                ...cmdbres.queryServiceTemplateList,
                data: {
                    bizId: biz.cm_unid,
                },
            });
            if (res && res.data) {
                res.data.map((item, index) => item.key=index);
                setTemplateData(res.data);
				if(info) {	//update
					querySetTemplateRelations(res.data);
				} else {
					setLoading(false);
				}
            } else {
                setTemplateData([]);
				setLoading(false);
            }
			
        } catch (error) {
            console.log(error);
        } 
    };

	const querySetTemplateRelations = async (arr) => {
		try {
            const res = await request({
                ...cmdbres.querySetTemplateRelations(info.id),
            });
            if (res && res.data) {
                const ids = res.data.map(item => item.id);
				const items = arr?.filter(item => ids.includes(item.id))||[];
				const _ids = items.map(item => item.id);
				onChange(_ids, arr);
				if (typeof onAddFinish == "function") onAddFinish(items);
            }
			setLoading(false);
        } catch (error) {
            console.log(error);
        } 
	}

	const onFinish = async (values) => {
		setVisible(false);
		const selectIds = values.serviceTemplates || [];
		const selectItems = templateData?.filter(item => selectIds.includes(item.id))
		if (typeof onAddFinish == "function") onAddFinish(selectItems);
	};

	const onCancel = () => {
		setVisible(false);
	}

	const content = (item)=> {
		return (
			<div>
				<p>模版名称：{item.name}</p>
				<p>服务分类ID：{item.serviceCategoryId}</p>
			</div>
		)
	};

	const [indeterminate, setIndeterminate] = useState(true);
	const [checkAll, setCheckAll] = useState(false);

	const onChange = (list, arr) => {
		arr = arr || templateData;
		setIndeterminate(!!list.length && list.length < arr.length);
		setCheckAll(list.length === arr.length);
		
		form.setFieldsValue({
			serviceTemplates: list
		})
	};

	const onCheckAllChange = (e) => {
		setIndeterminate(false);
		setCheckAll(e.target.checked);
		form.setFieldsValue({serviceTemplates: e.target.checked ? templateData.map(item=> item.id) : []});
	};

	return (
		<Modal
			title="添加服务模板"
			className="hcp-modal-md business"
			visible={visible}
			footer={null}
			onCancel={onCancel}
			// destroyOnClose
			maskClosable={false}
			// afterClose={()=>{form.resetFields()}}
		>
			<Form
				form={form}
				labelCol={{ span: 1 }}
				wrapperCol={{ span: 23 }}
				name="basic"
				onFinish={onFinish}
			>
				<div style={{marginBottom: 10}}>
					{/* <Space>
						<Input.Search
							placeholder="请输入模版名称"
							value={searchValue}
							onChange={(e) => {
								setSearchValue(e.target.value);
							}}
							// onSearch={}
							style={{ width: "210px" }}
							enterButton
						/>
					</Space> */}
					<div>
						<Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll} style={{border: 0, backgroundColor: 'white'}}>
							全选
						</Checkbox>
					</div>
				</div>
				 <Form.Item name="serviceTemplates">
					<Checkbox.Group onChange={onChange} style={{width: '100%'}} className="tempalte-checkbox">
						{
							templateData.map((item, index)=> (
								<Checkbox value={item.id} style={{ lineHeight: '32px', width:'auto' }} key={index}>
									<Popover placement="top" content={content(item)}> 
										<span className="checkbox-name">{item.name}</span>
									</Popover>
								</Checkbox>
							))
						}
					</Checkbox.Group>
				</Form.Item>
				<div className="hcp-modal-body-footer">
					<div style={{float: 'left'}}>
						<Form.Item
							noStyle
							dependencies={["serviceTemplates"]}
						>
							{({ getFieldValue }) => {
								let serviceTemplates = getFieldValue("serviceTemplates");
								return (
									<span>已选 {serviceTemplates?.length??0} 个  </span>
								)
							}}
						</Form.Item>
						<a onClick={()=>{history.push({pathname: '/business/serviceTemplate'});}}>跳转服务模板</a>
					</div>
					<Form.Item wrapperCol={{ span: 24 }} >
						<Button type="primary" htmlType="submit">确定</Button>
						<Button onClick={onCancel}>取消</Button>
					</Form.Item>
				</div>
			</Form>
		</Modal>
	)
}

export default ServiceTemplateModal;
